package com.byb.server.web.rest;

import com.byb.server.service.dto.Wc.WcProductDetialForFontEndDTO;
import com.byb.server.service.dto.Wc.WcProductForFontEndDTO;
import com.byb.server.service.dto.Wc.WcSearchProductDTO;
import com.codahale.metrics.annotation.Timed;
import com.byb.server.service.WcProductService;
import com.byb.server.web.rest.util.HeaderUtil;
import com.byb.server.web.rest.util.PaginationUtil;
import com.byb.server.service.dto.WcProductDTO;
import io.swagger.annotations.ApiParam;
import io.github.jhipster.web.util.ResponseUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.net.URI;
import java.net.URISyntaxException;

import java.util.List;
import java.util.Optional;
import java.util.stream.StreamSupport;

import static org.elasticsearch.index.query.QueryBuilders.*;

/**
 * REST controller for managing WcProduct.
 */
@RestController
@RequestMapping("/api")
public class WcProductResource {

    private final Logger log = LoggerFactory.getLogger(WcProductResource.class);

    private static final String ENTITY_NAME = "wcProduct";

    private final WcProductService wcProductService;

    public WcProductResource(WcProductService wcProductService) {
        this.wcProductService = wcProductService;
    }

    /**
     * POST  /wc-products : Create a new wcProduct.
     *
     * @param wcProductDTO the wcProductDTO to create
     * @return the ResponseEntity with status 201 (Created) and with body the new wcProductDTO, or with status 400 (Bad Request) if the wcProduct has already an ID
     * @throws URISyntaxException if the Location URI syntax is incorrect
     */
    @PostMapping("/wc-products")
    @Timed
    public ResponseEntity<WcProductDTO> createWcProduct(@RequestBody WcProductDTO wcProductDTO) throws URISyntaxException {
        log.debug("REST request to save WcProduct : {}", wcProductDTO);
        if (wcProductDTO.getId() != null) {
            return ResponseEntity.badRequest().headers(HeaderUtil.createFailureAlert(ENTITY_NAME, "idexists", "A new wcProduct cannot already have an ID")).body(null);
        }
        WcProductDTO result = wcProductService.save(wcProductDTO);
        return ResponseEntity.created(new URI("/api/wc-products/" + result.getId()))
            .headers(HeaderUtil.createEntityCreationAlert(ENTITY_NAME, result.getId().toString()))
            .body(result);
    }

    /**
     * PUT  /wc-products : Updates an existing wcProduct.
     *
     * @param wcProductDTO the wcProductDTO to update
     * @return the ResponseEntity with status 200 (OK) and with body the updated wcProductDTO,
     * or with status 400 (Bad Request) if the wcProductDTO is not valid,
     * or with status 500 (Internal Server Error) if the wcProductDTO couldn't be updated
     * @throws URISyntaxException if the Location URI syntax is incorrect
     */
    @PutMapping("/wc-products")
    @Timed
    public ResponseEntity<WcProductDTO> updateWcProduct(@RequestBody WcProductDTO wcProductDTO) throws URISyntaxException {
        log.debug("REST request to update WcProduct : {}", wcProductDTO);
        if (wcProductDTO.getId() == null) {
            return createWcProduct(wcProductDTO);
        }
        WcProductDTO result = wcProductService.save(wcProductDTO);
        return ResponseEntity.ok()
            .headers(HeaderUtil.createEntityUpdateAlert(ENTITY_NAME, wcProductDTO.getId().toString()))
            .body(result);
    }

    /**
     * GET  /wc-products : get all the wcProducts.
     *
     * @param pageable the pagination information
     * @return the ResponseEntity with status 200 (OK) and the list of wcProducts in body
     */
    @GetMapping("/wc-products")
    @Timed
    public ResponseEntity<List<WcProductDTO>> getAllWcProducts(@ApiParam Pageable pageable) {
        log.debug("REST request to get a page of WcProducts");
        Page<WcProductDTO> page = wcProductService.findAll(pageable);
        HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/wc-products");
        return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK);
    }

    /**
     * GET  /wc-products/:id : get the "id" wcProduct.
     *
     * @param id the id of the wcProductDTO to retrieve
     * @return the ResponseEntity with status 200 (OK) and with body the wcProductDTO, or with status 404 (Not Found)
     */
    @GetMapping("/wc-products/{id}")
    @Timed
    public ResponseEntity<WcProductDTO> getWcProduct(@PathVariable Long id) {
        log.debug("REST request to get WcProduct : {}", id);
        WcProductDTO wcProductDTO = wcProductService.findOne(id);
        return ResponseUtil.wrapOrNotFound(Optional.ofNullable(wcProductDTO));
    }

    /**
     * DELETE  /wc-products/:id : delete the "id" wcProduct.
     *
     * @param id the id of the wcProductDTO to delete
     * @return the ResponseEntity with status 200 (OK)
     */
    @DeleteMapping("/wc-products/{id}")
    @Timed
    public ResponseEntity<Void> deleteWcProduct(@PathVariable Long id) {
        log.debug("REST request to delete WcProduct : {}", id);
        wcProductService.delete(id);
        return ResponseEntity.ok().headers(HeaderUtil.createEntityDeletionAlert(ENTITY_NAME, id.toString())).build();
    }

    /**
     * SEARCH  /_search/wc-products?query=:query : search for the wcProduct corresponding
     * to the query.
     *
     * @param query the query of the wcProduct search
     * @param pageable the pagination information
     * @return the result of the search
     */
    @GetMapping("/_search/wc-products")
    @Timed
    public ResponseEntity<List<WcProductDTO>> searchWcProducts(@RequestParam String query, @ApiParam Pageable pageable) {
        log.debug("REST request to search for a page of WcProducts for query {}", query);
        Page<WcProductDTO> page = wcProductService.search(query, pageable);
        HttpHeaders headers = PaginationUtil.generateSearchPaginationHttpHeaders(query, page, "/api/_search/wc-products");
        return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK);
    }

    /**
     *
     * @param insurerId
     * @param categoryId
     * @return the ResponseEntity with status 200 (OK) and with body the WcSearchProductDTO, or with status 404 (Not Found)
     */
    @GetMapping("/wc-products-by-insurer-or-type")
    @Timed
    public ResponseEntity<List<WcProductForFontEndDTO>> getProductForWc(@RequestParam(value = "insurerId",required = false)  Long insurerId, @RequestParam(value = "categoryId",required = false)  Long categoryId, @ApiParam Pageable pageable) {
        log.debug("REST request to get search WcProducts for wC : {}", insurerId,categoryId);
        List<WcProductForFontEndDTO> result = wcProductService.getProdcutForWc(insurerId,categoryId,pageable);
        return new ResponseEntity<>(result, HttpStatus.OK);
    }

    @GetMapping("/wc-product-detail")
    @Timed
    public ResponseEntity<WcProductDetialForFontEndDTO> getPriductDetailForWc(@RequestParam Long id, @ApiParam Pageable pageable){
        log.debug("REST request to get  WcProductDetail for wC : {}",id);
        WcProductDetialForFontEndDTO wcProductDetialForFontEndDTO = wcProductService.getProductDetail(id,pageable);
        return ResponseUtil.wrapOrNotFound(Optional.ofNullable(wcProductDetialForFontEndDTO));
    }
    @GetMapping("/product/generate-rank")
    @Timed
    public ResponseEntity<Void> generateRank(){
        log.debug("REST request to generate ranking: {}");
        wcProductService.generate();
        return ResponseEntity.ok().headers(HeaderUtil.createEntityDeletionAlert(ENTITY_NAME, "successful")).build();
    }

    @GetMapping("/product/batch-product")
    @Timed
    public ResponseEntity batchProduct(@RequestBody List<WcProductDTO> list){
        log.debug("REST request to batch product: {}");
         wcProductService.saveBatchProduct(list);
        return ResponseEntity.ok(true);
    }

}
